<template>
  <div>
      <div v-if="disabled">
          <el-select :style="{ width: width }" :clearable="clearable" placeholder="请选择" ref="ddlrptunitSelect" v-model="myvalue" filterable :disabled="disabled" :filter-method="filterMethod">
              <!-- :filter-method="filterMethod" -->
              <el-option :key="item.instrid" :label="item.instrname + ' [' + item.instrid + ']'" :value="item.instrid" v-for="item in options">
                  <span style="float: left">{{ item.instrname }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ item.instrid }}
                  </span>
              </el-option>
          </el-select>
      </div>
      <div v-else>
          <el-select :style="{ width: width }" :clearable="clearable" @change="changevt" @keyup.space.native="popbigtab" @dblclick.native="popbigtab" placeholder="请选择" ref="ddlrptunitSelect" v-model="myvalue" filterable :filter-method="filterMethod">
              <el-option :key="item.instrid" :label="item.instrname + ' [' + item.instrid + ']'" :value="item.instrid" v-for="item in options">
                  <span style="float: left">{{ item.instrname }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ item.instrid }}
                  </span>
              </el-option>
          </el-select>
      </div>
      <el-dialog :append-to-body="appendtobody" :close-on-click-modal="false" :visible.sync="dialogTableVisible" title="请选择检验仪器" :destroy-on-close="true">
          <table v-if="this.$ddldata.IsAreaMode&&bPower">
              <tr>
                  <td style="font-size:12px; width:30px;">医院</td>
                  <td>
                      <rm-ddl-common v-if="this.$ddldata.IsAreaMode&&bPower" @change="hospitalchange" datatype="areahospital" dataname="医院" v-model="hospitalval" width="300px" :clearable="false"></rm-ddl-common>
                  </td>
              </tr>
          </table>
          <div v-if="multiple_choice" style="text-align:right;margin:5px;">
              <el-button icon="el-icon-check" @click="btnSure()">确定</el-button>
              <el-button icon="el-icon-close" @click="btnCancel()">取消</el-button>
          </div>
          <el-container style="height: 500px">
              <el-aside width="150px">
                  <el-menu class="emitem-nav" @select="handleclsSelect" :default-active="groupid">
                      <el-menu-item index="全部">全部</el-menu-item>
                      <el-menu-item :index="emitem.name" :key="index" v-for="(emitem, index) in clsMenus">{{ emitem.name }}</el-menu-item>
                  </el-menu>
              </el-aside>
              <el-container style="overflow: hidden">
                  <el-main style="overflow: hidden">
                      <vxe-grid :columns="tableColumn" :display-pager="false" :pager-config="tablePage" :proxy-config="tableProxy" @cell-dblclick="vxselect" border height="498px" highlight-current-row highlight-hover-row ref="ddlinstridTable" resizable size="mini" stripe :sort-config="{ trigger: 'cell' }"></vxe-grid>
                  </el-main>
              </el-container>
          </el-container>
      </el-dialog>
  </div>
</template>
<script>
// import { close } from "fs";
import XE from "xe-utils";
export default {
  props: {
      width: { type: String, default: "200px" },
      value: [Number, String],
      appendtobody: { type: Boolean, default: true },
      clearable: { type: Boolean, default: true },
      defaultflag: { type: String, default: "" },
      prgno: { type: String },
      germflag: { tyoe: String },
      disabled: { type: Boolean, default: false },
      labgroupid: { type: Number, default: 0 },
      hospcode: { type: String, default: "" },
      bPower: { type: Boolean, default: false },
      multiple_choice: { type: Boolean, default: false },
      beforeChange: { type: Function },
  },

  data() {
      return {
          selvalue: 0,
          hospitalval: "",
          myvalue: this.value,
          fulldata: null,
          groupid: "全部",
          clsMenus: [],
          tableColumn: [],
          finallvalue: [],
          tablePage: {
              pageSize: 1000,
          },
          tableProxy: {
              index: true, // 启用动态序号代理
              // 配置响应的数据属性
              props: {
                  result: "data.result",
                  total: "data.page.total",
              },
              ajax: {
                  // page 对象： { pageSize, currentPage }
                  query: (param) => {
                      let _this = this;
                      return new Promise((s, f) => {
                          var collist = [];
                          if (this.multiple_choice) {
                              //多选模式
                              collist = [
                                  {
                                      type: "selection",
                                      width: 40,
                                      align: "center",
                                  },
                              ];
                              for (let i = 0, len = this.fulldata.Cols.length; i < len; i++) {
                                  const item = this.fulldata.Cols[i];
                                  let colitem = {
                                      field: item.field,
                                      title: item.title,
                                      width: item.width,
                                      sortable: true,
                                  };
                                  collist.push(colitem);
                              }
                              this.tableColumn = collist;
                          } else {
                              for (let i = 0, len = this.fulldata.Cols.length; i < len; i++) {
                                  const item = this.fulldata.Cols[i];
                                  let colitem = {
                                      field: item.field,
                                      title: item.title,
                                      width: item.width,
                                      sortable: true, // 添加列头点击排序
                                  };
                                  collist.push(colitem);
                              }
                              this.tableColumn = collist;
                          }
                          //根据groupid过滤
                          let cData = this.fulldata.Data;
                          if (this.groupid != "全部") {
                              //  开窗后自动选择当前工作组，过滤数据后选中当前仪器ID所在行。需要页面绑定v-model。
                              cData = cData.filter((item) => item.labgroupname === this.groupid);
                              cData.forEach((e) => {
                                  if (e.instrid == XE.toString(this.value)) {
                                      var row = this.$refs.ddlinstridTable.getRowById(e._XID);
                                      this.$refs.ddlinstridTable.setCurrentRow(row);
                                      this.$refs.ddlinstridTable.scrollToRow(row);
                                  }
                              });
                          }
                          //分页
                          // var pagedData = cData.slice((param.page.currentPage - 1) * param.page.pageSize, param.page.currentPage * param.page.pageSize);
                          s({ data: { page: { total: cData.length }, result: cData } });
                      });
                  },
              },
          },
          seloptions: [],
          options: [],
          dialogTableVisible: false,
          myname: "",
          finallname: [],
      };
  },
  watch: {
      value(newVal) {
          this.myvalue = newVal;
          if (this.seloptions.length > 0) {
              if (this.defaultflag == "1") {
                  if (!this.myvalue || this.myvalue == "" || this.myvalue == "0") {
                      this.$emit("change", XE.toString(this.myvalue), "");
                      this.$emit("changeObj", {code:XE.toString(this.myvalue), name:'',row :""});
                      this.$emit("input", XE.toString(this.myvalue));
                  } else {
                      let ftmp = this.seloptions.filter((item) => item.instrid === XE.toString(this.myvalue));
                      if (ftmp && ftmp.length > 0) {
                      } else {
                          this.myvalue = this.seloptions[0].instrid;
                          this.myname = this.seloptions[0].instrname;
                          this.$emit("change", this.myvalue, this.myname);
                          this.$emit("changeObj", {code:this.myvalue, name:this.myname,row :""});
                          this.$emit("input", this.myvalue);
                      }
                  }
              }
          }
      },
      myvalue(newVal) {
          this.$emit("input", XE.toString(newVal));
      },
      dialogTableVisible(opendiv) {
          if (opendiv) {
              let data = this.fulldata.Data.find((m) => m.instrid == this.value);
              if (!!data) this.groupid = data.labgroupname;
              this.handleclsSelect(this.groupid, "");
          } else {
              this.groupid = "全部";
          }
      },
  },
  computed: {
      myappendtobody: function () {
          return this.appendtobody;
      },
  },
  created() {
      this.$ddldata.IsAreaModeFun().then((r) => {
          if (this.$ddldata.IsAreaMode) {
              this.hospitalval = this.$tool.getSession(this.$tool.selectedhis);
          }
          this.loadAllData();
      });
  },
  methods: {
      handleclsSelect: function (key, keyPath) {
          this.groupid = key;
          setTimeout(() => {
              if (this.multiple_choice) {
                  this.SelectRecordsSet();
              }
              this.$refs.ddlinstridTable.commitProxy("query");
          }, 30);
      },
      setCurrentValue: async function (v) {
          this.selvalue = v;
          if (!this.fulldata) {
              await this.loadAllData();
          }
          if (this.selvalue) {
              if (this.selvalue.toString().indexOf(",") > 0) {
                  let ids = this.selvalue.toString().split(",");
                  let datas = this.fulldata.Data.filter((m) => ids.indexOf(m.rptunitid.toString()) > -1);
                  if (datas && datas.length > 0) this.$refs.ddlinstridTable.setSelection(datas, true);
              } else {
                  let data = this.fulldata.Data.find((m) => m.instrid == this.selvalue);
                  if (!!data) this.groupid = data.labgroupname;
                  this.handleclsSelect(this.groupid, "");
              }
          } else {
              this.groupid = "全部";
              this.handleclsSelect(this.groupid, "");
          }
      },
      SelectRecordsSet() {
          let data = this.$refs.ddlinstridTable.getSelectRecords(); //当前页面选中的数据
          let rdata = this.$refs.ddlinstridTable.tableData; //当前页面所有的数据
          let instridarr = [];
          data.forEach((element) => {
              instridarr.push(element.instrid);
          });
          try {
              rdata.forEach((element) => {
                  if (data.length > 0) {
                      //当前页面有勾选的项目
                      if (instridarr.indexOf(element.instrid) > -1) {
                          //勾选的数据是当前数据
                          if (this.finallvalue.indexOf(element.instrid) < 0) {
                              this.finallvalue.push(element.instrid);
                              this.finallname.push(element.instrname)
                          }
                      } else {
                          if (this.finallvalue.indexOf(element.instrid) > -1) {
                              let index = this.finallvalue.indexOf(element.instrid);
                              this.finallvalue.splice(index, 1);
                              this.finallname.splice(index, 1);
                          }
                      }
                  } else {
                      //当前页面没有勾选的项目
                      if (this.finallvalue.indexOf(element.instrid) > -1) {
                          let index = this.finallvalue.indexOf(element.instrid);
                          //返回值的里面有则删除
                          this.finallvalue.splice(index, 1);
                          this.finallname.splice(index, 1);
                      }
                  }
              });
          } catch (e) {}
      },
      async btnSure() {
          this.SelectRecordsSet();
          var v = this.finallvalue.join(","); // this.finallvalue.substring(0, this.finallvalue.length - 1);
          var n = this.finallname.join(",");
          let execflag = true;
          if (typeof this.beforeChange === "function") {
              let r = await this.beforeChange(v);
              // console.log("🤣 ~  r",  r);
              // if (!r) {
              //     execflag = false;
              // }
          }
          if (execflag) {
              this.$nextTick(() => {
                  this.$emit("change", v, n);
                  this.$emit("changeObj", {code:v, name:n,row :""});
                  this.dialogTableVisible = false;
              });
          }
      },
      btnCancel() {
          this.$emit("cancel");
          this.dialogTableVisible = false;
      },
      popbigtab: function (evt) {
          this.$refs.ddlrptunitSelect.blur();
          this.dialogTableVisible = true;
      },
      hospitalchange(code) {
          this.hospitalval = code;
          this.loadAllData(1);
      },
      changevt: function (evt) {
          let cData = this.fulldata.Data;
          var evtname = "";
          var sobj = null;
          if (evt && evt != "0") {
              cData = cData.filter((item) => item.instrid === evt);
              if (cData && cData.length > 0) {
                  evtname = cData[0].instrname;
                  sobj = cData[0];
              }
          }
          this.$nextTick(() => {
              this.$refs.ddlrptunitSelect.focus();
              this.$emit("change", evt, evtname, sobj);
              this.$emit("changeObj", {code:evt, name:evtname, row:sobj});
          });
      },
      getcurrenthosp() {
          this.$tool
              .request({
                  url: "/ucent/ddl",
                  method: "post",
                  data: {
                      action: "querybydbclick",
                      colname: colname,
                      qvalue: qvalue,
                      tablename: tablename,
                      LogDatetime1: this.LogDatetime1,
                      LogDatetime2: this.LogDatetime2,
                  },
              })
              .then((res) => {
                  this.popcontentright = res;
                  this.poploading = false;
              })
              .catch(() => {
                  this.poploading = false;
              });
      },
      loadAllData: function (flag) {
          this.clsMenus = [];
          this.$tool
              .request({
                  url: "ucent/ddl",
                  method: "post",
                  data: {
                      action: "instrument",
                      groupid: this.groupid,
                      prgno: this.prgno,
                      hospcode: this.hospitalval == "" ? this.hospcode : this.hospitalval,
                      labgroupid: this.labgroupid,
                  },
              })
              .then((res) => {
                  var tmpData = res.RData;
                  tmpData.Data.forEach((e) => {
                      e.inputcode = this.$pub.CreateInputcode(e.instrname, this, 20);
                  });
                  this.fulldata = tmpData;
                  this.seloptions = this.fulldata.Data;
                  this.options = this.fulldata.Data;
                  //左边分类
                  var instrname = "";
                  let clsArray = [];
                  for (let i = 0; i < this.fulldata.Data.length; i++) {
                      let cfData = this.fulldata.Data[i];
      
                      if (cfData.instrid == this.myvalue) {
                          instrname = cfData.instrname;
                      }
                      if (
                          clsArray.find((x) => {
                              return x.name === cfData.labgroupname;
                          }) == undefined
                      ) {
                          let citem = { name: cfData.labgroupname, seq: cfData.seq2 };
                          clsArray.push(citem);
                      }
                  }
                  clsArray.sort(function (a, b) {
                      return a.seq - b.seq;
                  });
                  this.clsMenus = clsArray;
                  if (flag == 1) {
                      this.groupid = "全部";
                      setTimeout(() => {
                          this.$refs.ddlinstridTable.commitProxy("query");
                      }, 30);
                  } else {
                      //仪器根据本地默认仪器选项取值,若无则取第一个仪器
                      if (this.seloptions.length > 0) {
                          if (this.defaultflag == "1") {
                              if (!this.myvalue || this.myvalue == "" || instrname == "") {
                                  this.myvalue = res.defid;

                                  let data = this.fulldata.Data.find((m) => m.instrid == XE.toString(this.myvalue));
                                  if (data) instrname = data.instrname;
                              }
                              if (!this.myvalue || this.myvalue == "" || instrname == "") {
                                  this.myvalue = this.seloptions[0].instrid;
                                  //this.$emit("change", this.myvalue);
                              } else {
                                  let ftmp = this.seloptions.filter((item) => item.instrid === XE.toString(this.myvalue));
                                  if (ftmp && ftmp.length > 0) {
                                  } else {
                                      this.myvalue = this.seloptions[0].instrid;
                                  }
                              }
                              let cData = this.fulldata.Data;
                              var evtname = "";
                              var sobj = null;
                              if (this.myvalue && this.myvalue != "0") {
                                  cData = cData.filter((item) => item.instrid == this.myvalue);
                                  if (cData && cData.length > 0) {
                                      evtname = cData[0].instrname;
                                      sobj = cData[0];
                                  }
                              }
                              this.$emit("change", this.myvalue, evtname, sobj);
                              this.$emit("changeObj", {code:this.myvalue, name:evtname, row:sobj});
                          }
                      }
                  }
              })
              .catch((e) => {
                  console.log("erro", e);
                  f(e);
              });
      },
      vxselect: function (data, evt) {
          this.myvalue = data.row.instrid;
          this.dialogTableVisible = false;
          this.$nextTick(() => {
              this.$refs.ddlrptunitSelect.blur();
              this.$emit("change", this.myvalue, data.row.instrname, data.row);
              this.$emit("changeObj", {code:this.myvalue, name:data.row.instrname, row:data.row});
          });
      },
      // 添加搜索过滤的方法 用于查询拼音吗
      filterMethod(query) {
          if (query) {
              //val存在
              this.options = this.seloptions.filter((item) => {
                  if (item.hasOwnProperty("inputcode")) {
                      if (!!~item.instrname.indexOf(query) || !!~item.instrid.indexOf(query) || (item.inputcode ? !!~item.inputcode.toUpperCase().indexOf(query.toUpperCase()) : false)) {
                          return true;
                      }
                  } else {
                      if (!!~item.instrname.indexOf(query) || !!~item.instrid.indexOf(query)) {
                          return true;
                      }
                  }
              });
          } else {
              //val为空时，还原数组
              this.options = this.seloptions;
          }
      },
  },

  // mounted() {
  //     this.loadAllData();
  // },
};
</script>
<style scoped>
.el-aside {
  color: #333;
  border: solid #cccccc;
  border-width: 1px 0 1px 1px;
  background-color: #f5f5f5;
}
.el-menu {
  border: none;
  background-color: #f5f5f5;
}
.el-main {
  padding: 0;
}
/deep/ .emitem-nav .el-menu-item {
  height: 28px !important;
  line-height: 28px !important;
}
</style>
